<template>
  <el-drawer :visible.sync="visible" size="500px" :show-close="false" ref="drawer">
    <template v-if="init">
      <div class="header-title" :class="`header-title-${agendaInfo.type}`" slot="title">
        <span>{{$t('calendar.detail.agendaDetail')}}</span>
        <div class="opt">
          <!-- <i class="iconfont icon-bell"></i>  -->
          <el-tooltip :content="$t('common.base.edit')" placement='top'>
            <i v-show="canEdit" class="iconfont icon-edit-square agenda-pointer" @click="edit"></i> 
          </el-tooltip> 
          
          <el-tooltip :content="$t('common.base.delete')" placement='top'>
            <i v-show="canDel" class="iconfont icon-delete agenda-pointer" @click="showDialog('del')"></i> 
          </el-tooltip>

          <el-tooltip :content="$t('common.base.cancel')" placement='top'>
            <i v-show="canCancel" class="iconfont icon-stop agenda-pointer" @click="cancel"></i> 
          </el-tooltip>  
          <i class="iconfont icon-yemianshanchu" @click="close"></i> 
        </div>
      </div>

      <div class="content">
        <p class="content-title" :class="cancelType.length > 0 ? 'content-cancel' : ''">{{cancelType}}{{agendaInfo.name}}</p>
        <p><i class="iconfont icon-fdn-datetime"></i>
          {{ $t('calendar.detail.timeRange', { start: start, end: end}) }}
        </p>
        <p>
          <span class="task-pointer" v-user="agendaInfo.createUser">
            <i class="iconfont icon-fdn-user"></i>
            <img :src="head(agendaInfo.createUserHead)"/>
            <template v-if="isOpenData && agendaInfo.createUserStaffId">
              <open-data :openid="agendaInfo.createUserStaffId"></open-data>{{$t('common.base.create3')}}
            </template>
            <template v-else>
              {{$t('calendar.detail.creater', {createUserName: agendaInfo.createUserName})}}
            </template>
          </span>
        </p>
        <p v-if="agendaInfo.isRepeat === 1">
          <i class="iconfont icon-sync"></i>
          {{agendaInfo.repeatType ===1 ? $t('calendar.detail.repeatEveryDay'): agendaInfo.repeatType ===2 ? $t('calendar.detail.repeatEveryWeek') : agendaInfo.repeatType ===3 ? $t('calendar.detail.repeatEveryMonth') : $t('calendar.detail.repeatEveryYear') }}
        </p>
        <p v-if="!agendaInfo.noticeContent && !agendaInfo.minutes"><i class="iconfont icon-bell1"></i>{{$t('calendar.detail.noMind')}}</p>
        <p v-if="agendaInfo.minutes"><i class="iconfont icon-bell1"></i>{{$t('calendar.detail.agendaText', {data1: agendaInfo.noticeType == 1 ? $t('common.base.start') : $t('common.base.end') , data2: agendaInfo.minutes})}}</p>
        <div v-if="agendaInfo.noticeContent" class="notice-content"> {{$t('calendar.detail.remindText')}}【<biz-comment-html :html="agendaInfo.noticeContent"/>】</div>
        <div v-if="agendaInfo.descr" class="mar-b-24">
          <div :style="{height: descHeight}" ref="descrRef" class="agendainfo-desc flex">
            <i class="iconfont icon-shijian1"></i>
            <div :class="['descr-content', isShowMoreBtn && !isOpen ? 'more-desc' : '']">{{ agendaInfo.descr }}</div>
          </div>
          <div
            v-if="isShowMoreBtn"
            class="descr-more"
            @click="isOpen = !isOpen"
          >
            <div v-if="!isOpen">
              <span>{{$t('common.base.more')}}</span>
              <i class="iconfont icon-fdn-select"></i>
            </div>
            <i v-else class="el-icon-arrow-up"></i>
          </div>
        </div>
      </div>

      <el-tabs class="agenda-users" v-if="userList.length">
        <el-tab-pane :label="item.label" v-for="item in userList" :key="item.id">
          <el-button v-if="canAddUser && item.id == 1" class="add-users-btn" icon="el-icon-plus" size="small" @click="selectApproveUser">{{$t('common.base.add2')}}</el-button>
          <template v-if="!item.users.length">
            <span class="no-user">{{$t('calendar.detail.noStatusPerson')}}</span>
          </template>
          <template v-else>
            <el-tag
              :key="user.userId"
              v-for="user in item.users"
              disable-transitions
              :closable="user.userId == createUserId || !canDelUser ? false : true"
              @close="delAgendaUser(user)"
              type='info'
              size="medium">
              <span class="task-pointer" v-user="user.userId">
                <img :src="head(user.userHead)">
                <template v-if="isOpenData && user.staffId">
                  <open-data :openid="user.staffId"></open-data>
                </template>
                <template v-else>
                  {{user.displayName || user.userName}}
                </template>
              </span>
            </el-tag>
          </template>
        </el-tab-pane>
      </el-tabs>
  
      <el-tabs>
        <el-tab-pane :label="$t('common.base.dynamicInfo')">
          <base-timeline 
            :data="agendalog" 
            :record-render="renderRecord" 
          />
        </el-tab-pane>
      </el-tabs>
      <div v-if="detail.reject && detail.accept" class="btn-group">
        <div>
          <el-button type="danger" @click="showDialog(2)" :disabled="pending">{{$t('calendar.refuseAgenda')}}</el-button>
          <el-button type="primary" @click="showDialog(1)" :disabled="pending">{{$t('calendar.acceptAgenda')}}</el-button>
        </div>
      </div>
    </template>

    <el-dialog
      :visible.sync="dialogVisible"
      :modal-append-to-body="false"
      width="30%">
      <div slot="title" class="dialog-title">
        <i class="el-icon-warning-outline"></i>
        <span>&nbsp;{{$t('calendar.detail.oprate', {dialogTxt: dialogTxt})}}</span>
      </div>
      <p>{{$t('calendar.detail.dialogText', {dialogTxt: dialogTxt})}}</p>
      <div class="dialog-content">
        <el-radio v-model="radio" label="one">{{$t('calendar.detail.onlyThisTime')}}</el-radio>
        <el-radio v-model="radio" label="all">{{$t('calendar.detail.allAgenda')}}</el-radio>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="dialogSubmit">{{$t('common.base.makeSure')}}</el-button>
      </span>
    </el-dialog>

  </el-drawer>
</template>

<script>
import { formatDate } from 'pub-bbx-utils';  
import { isAllotByDepartment, isOpenData } from '@src/util/platform'
import * as CalendarApi from '@src/api/CalendarApi.ts'
import { getOssUrl } from '@src/util/assets'
const defaultAvatar = getOssUrl('/avatar.png')
import { safeNewDate } from '@src/util/time';
/* api */
import { getSelectDepartmentCalendarUserList } from '@src/component/common/BaseSelectUser/api'
import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser/model/enum'

const descMaxHeight = 44; // 日程描述默认最多显示两行的高度（一行22px）

export default {
  name: 'agenda-detail',
  inject:['initData'],
  props: {
    // agendaId: {
    //   type: Number | String,
    //   default: '',
    // },
  },
  data() {
    return {
      isOpenData,
      pending: false,
      visible: false,
      detail: {},
      init: false,

      currentId: '',
      start: '',
      end: '',
      enterType: '', // 从哪里进 index为日程页面进入
      agendaId: '',
      dialogVisible: false,
      radio: 'one',
      acceptType: -1,
      notificationEnable: false,
      isShowMoreBtn: false, // 日程详细是否显示更多按钮
      isOpen: true, // 是否展开 true:展开
    }
  },
  computed: {
    // 日程详情的高度
    descHeight() {
      return this.isOpen ? 'auto' : `${descMaxHeight}px`;
    },
    agendaInfo(){
      return this.detail.agendaInfo
    },
    cancelType(){
      let cancelType = '';
      let userId = this.loginUser?.userId;
      this.users.forEach((item) => {
        if(item.userId == userId && item.status == 2){
          cancelType = this.$t('calendar.detail.refused');
        }
      });

      return this.agendaInfo.cancel == 1 ? this.$t('calendar.detail.canceled') : cancelType
    },
    createUserId(){
      return this.agendaInfo?.createUser
    },
    startTime(){
      return this.agendaInfo?.startTime
    },
    endTime(){
      return this.agendaInfo?.endTime
    },
    agendalog(){
      return this.detail.agendalog
    },
    users(){
      return this.detail.users
    },
    type(){
      return this.agendaInfo?.type 
    },
    all(){
      return this.$t('calendar.detail.allParticipants', {length: this.users?.length})
    },
    acceptUsers(){
      return this.users?.filter(item=>item.status == 1)
    },
    acceptLabel(){
      return this.$t('calendar.detail.allAccepted', {length: this.acceptUsers?.length})
    },
    refuseUsers(){
      return this.users?.filter(item=>item.status == 2)
    },
    refuseLabel(){
      return this.$t('calendar.detail.allRefused', {length: this.refuseUsers?.length})
    },
    userList(){
      let arr = []
      arr.push({id:1, label: this.all, users: this.detail.users})
      arr.push({id:2, label: this.acceptLabel, users: this.acceptUsers})
      arr.push({id:3, label: this.refuseLabel, users: this.refuseUsers})
      return arr
    },
    canCancel(){
      return this.detail.canCancel
    },
    canEdit(){
      return this.detail.canEdit
    },
    canDel(){
      return this.detail.canDel
    },
    canAddUser(){
      return this.detail.canAddUser
    },
    canDelUser(){
      return this.detail.canDelUser
    },
    canDo(){
      return this.detail.canDo
    },
    loginUser(){
      return this.initData?.loginUser 
    },
    dialogTxt(){
      if(this.acceptType == 1) {
        return this.$t('common.base.accept');
      }else if(this.acceptType == 2) {
        return this.$t('common.base.refuse');
      }
      return this.$t('common.base.delete');
      
    }
  },
  methods: {
    // 每次进入重新请求数据
    showDetail(timeInfo = {}) {
      this.visible = true
      this.start = formatDate(safeNewDate(timeInfo.start), 'yyyy-MM-dd HH:mm');
      this.end = formatDate(safeNewDate(timeInfo.end), 'yyyy-MM-dd HH:mm');
      this.agendaId = timeInfo.agendaId;
      this.notificationEnable = false;
      this.notificationEnable = timeInfo.notificationEnable
      if(this.notificationEnable) {
        const params = {}
        params.agendaId = this.agendaId
        this.getAgendaInfo(params)
      }else {
        this.getAgendaInfo(this.getParams())
      }
    },
    getParams(){
      const params = {}
      params.agendaId = this.agendaId
      params.startTime = safeNewDate(this.start).getTime()
      params.endTime = safeNewDate(this.end).getTime()
      return params
    },
    edit(){
      this.close();
      this.$emit('edit', this.agendaId);
    },
    del(api = 'deleteAgenda'){
      this.dialogVisible = false;
      this.$emit('del', { agendaId: this.agendaId, deleteTime: this.start, api}); 
    },
    cancel(){
      this.$emit('cancel', this.agendaId); 
    },
    close(){
      this.$refs.drawer.closeDrawer();
    }, 
    head(src){
      if(!src) return defaultAvatar;
      return src;
    },
    // 获取日程详情
    async getAgendaInfo(params) {
      try {
        const res = await CalendarApi.getAgendaCalendarInfo(params)
        if (res.status != 0) {
          return this.$platform.notification({
            title: res.message,
            type: 'error',
          })
        }
        if(!this.init) this.init = true
        this.detail = res.data || {}
        // 从通知中心进来需要修改计划开始和完成时间
        if(this.notificationEnable) {
          this.start = formatDate(safeNewDate(this.detail.agendaInfo.startTime), 'yyyy-MM-dd HH:mm');
          this.end = formatDate(safeNewDate(this.detail.agendaInfo.endTime), 'yyyy-MM-dd HH:mm');
          this.notificationEnable = false;
        }
        this.getDescHeight();
      } catch (err) {
        console.error('err', err)
      }
    },
    getDescHeight() {
      this.isOpen = true;
      this.isShowMoreBtn = false;
      // 获取日程详情的初始高度
      this.$nextTick(() => {
        if(this.agendaInfo?.descr) {
          let height = this.$refs.descrRef?.offsetHeight
          if(height > descMaxHeight) { // 若日程描述的高度大于两行的高度，默认需要只显示两行，显示更多
            this.isOpen = false; // 不展开日程描述
            this.isShowMoreBtn = true; // 显示更多
          }
        }
      })
    },
    renderRecord(h, item){
      if(!item.content) return
      try {
        const content = JSON.parse(item.content) || {}
        const { operater, participant, operaterStaffId, participantStaffId, action } = content
        const map = {
          'create': this.$t('common.base.create3'), 
          'update':this.$t('common.base.update'), 
          'accept': this.$t('common.task.button.accept'), 
          'refuse': this.$t('common.task.exceptionStatus.refused')
        }
        if (action == 'addUer') {
          return <i18n path="common.record.calendar.joinCalendar" tag="h5">
              <span place="operator">{this.renderUserName(operater, operaterStaffId)}</span>
              <span place="recipient">{this.renderSynergyName(participant, participantStaffId)}</span>
          </i18n>
        } else if (action == 'deleteUer') {
          return <i18n path="common.record.calendar.removeCalendar" tag="h5">
              <span place="operator">{this.renderUserName(operater, operaterStaffId)}</span>
              <span place="recipient">{this.renderSynergyName(participant, participantStaffId)}</span>
          </i18n>
        } 
        return <i18n path={`common.record.calendar.action.${action}`} tag="h5">
          <span place="operator">{this.renderUserName(operater, operaterStaffId)}</span>
        </i18n>
      } catch (error) {
        console.warn(error);
      }
    },
    renderUserName(userName, staffId){
      if(this.isOpenData && staffId) return <strong>{<open-data type="userName" openid={staffId}></open-data>}</strong>
      return <strong>{userName}</strong>
    },
    renderSynergyName(synergy, synergyStaffId){
      if(this.isOpenData && synergyStaffId) {
        const sids = synergyStaffId.split(',')
        if(sids.length) return sids.map(item=><open-data key={item} type="userName" openid={item}></open-data>) 
      }
      return synergy
    },
    async accept(status, api = 'setAgendaUserStatus'){
      if(status == 2) {
        if (!(await this.$platform.confirm(this.$t('calendar.refuseConfirm')))) return;
      }
      let params = {agendaId:this.agendaId, status};
      if(api === 'setAgendaUserStatusOne'){
        params.operatTime = this.startTime;
      }
      try {
        this.pending = true;
        const res = await CalendarApi[api](params);
        this.pending = false;
        if(res.status != 0) {
          return this.$platform.notification({
            title: res.message,
            type: 'error'
          });
        }
        this.dialogVisible = false;
        this.$platform.notification({
          title: this.$t('common.base.tip.operationSuccess'),
          type: 'success'
        });
        this.getAgendaInfo(this.getParams());
      } catch (err) {
        this.pending = false;
        console.error('err', err);
      }
    },
    async addAgendaUsers(users){
      try {
        const res = await CalendarApi.addAgendaUser({agendaId:this.agendaId, users});
        if(res.status != 0) {
          return this.$platform.notification({
            title: res.message,
            type: 'error'
          });
        }
        this.$platform.notification({
          title: this.$t('common.base.tip.operationSuccess'),
          type: 'success'
        });
        this.getAgendaInfo(this.getParams());
      } catch (err) {
        console.error('err', err);
      }
    },
    async delAgendaUser(userInfo){
      const user = {
        userId: userInfo.userId,
        userName: userInfo.userName
      }
      
      try {
        const res = await CalendarApi.delAgendaUser({agendaId:this.agendaId, user});
        if(res.status != 0) {
          return this.$platform.notification({
            title: res.message,
            type: 'error'
          });
        }
        this.$platform.notification({
          title: this.$t('common.base.tip.operationSuccess'),
          type: 'success'
        });
        this.getAgendaInfo(this.getParams());
      } catch (err) {
        console.error('err', err);
      }
    },
    async selectApproveUser(){
      let selected = this.users.map(item=>{
        item.displayName = item.userName
        item.head = item.userHead
        item.id = item.userId
        return item
      });

      let flag = isAllotByDepartment()
      // let selected = []
      let options = {
        title: this.$t('calendar.detail.selectParticipants'), // [选填] 默认值为 '请选择人员'
        max: -1, // [选填]最大人数：当值小于等于0或者不填时，不对选择人数做限制，max值为1时单选，大于1时多选
        selected, // [选填] 已选人员 每个人员必须包括userId,displayName,staffId,head这四个属性，只有带max大于1时生效
        unique: false,
        mode: BaseSelectUserModeEnum.Filter,
        // haveRole: true,
        // isCalendar: true,
        // calendarAction: `/calendar/add/user/tree?allotByTag=${!flag}`,
        // calendarSeeAllOrg: !flag,
        fetchDepartmentList: (params) => {
          
          const newParams = {
            ...params,
            allotByTag: !flag
          }
          
          return getSelectDepartmentCalendarUserList(newParams)
        }
      }
      
      /* FIXME: 选人组件 */
      this.$fast.select.multi.user(options)
        .then((res) => {
          if (res.status != 0 || !res.data) return
          let list = res.data.users || []
          // const userIds = [...this.users, ...list].map(item=>item.userId)
          // this.addAgendaUsers([...new Set(userIds)]) 
          const userIds = list.map(item=>{
            return {
              userId: item.userId,
              userName: item.displayName
            };
          })
          this.addAgendaUsers(userIds) 
        })
        .catch((err) => {
          console.warn(err)
        })
    },
    // 弹窗
    showDialog(status){
      if(status == 'del' && (this.agendaInfo.isRepeat == 0 || this.detail.isCreater)) return this.del();
      if(this.agendaInfo.isRepeat == 0) return this.accept(status);
      
      this.acceptType = status;
      this.radio = 'one';
      this.dialogVisible = true;
    },
    dialogSubmit(){
      if(this.acceptType == 'del'){
        this.radio == 'one' ? this.del() : this.del('deleteAllAgenda')
      }else {
        if(this.radio == 'one'){
          this.accept(this.acceptType, 'setAgendaUserStatusOne');
        }else {
          this.accept(this.acceptType);
        }
      }
    }
  },
}
</script>

<style lang="scss" scoped>
::v-deep .el-drawer__header{
  padding: 0;
  margin-bottom: 0px;
  box-sizing: border-box;
}

::v-deep .el-drawer__body{
  overflow-y: scroll;
  margin-top: 10px;
}

.header-title{
  display: flex;
  justify-content: space-between;
  padding: 10px 20px;
  color: #fff;
  i{
    margin-left: 15px;
  }
  .el-dropdown {
    .iconfont {
      color: #fff;
    }
  }
  .agenda-pointer {
    cursor: pointer;
  }
}

.header-title-2{
  background: $color-primary-light-6;
}
.header-title-1{
  background: #faae14;
}
.header-title-3{
  background: rgb(76, 175, 80);
}

.content{
  padding: 0 20px;
  img {
    height: 30px;
    width: 30px;
    border-radius: 50%;
    object-fit: cover;
    margin-right: 4px;
  }
  p {
    display: flex;
    align-items: center;
  }
  i {
    font-size: 16px;
    margin-right: 8px;
  }
  .content-title {
    font-size: 18px;
  }
  .content-cancel{
    text-decoration: line-through;
  }
  .notice-content{
    margin-left: 20px;
  }
}
.agenda-users{
  ::v-deep .el-tabs__content{
    display: flex;
    .el-tab-pane {
      display: flex;
      flex-wrap: wrap;
    }
    .add-user{
      height: 28px;
      padding: 4px 10px;
      border: 1px dashed;
      border-radius: 4px;
      margin-left: 20px;
      margin-right: -5px;
    }
    .el-tag{
      border-radius: 4px;
      margin-bottom: 12px;
      img {
        width: 24px;
        height: 24px;
        border-radius: 50%;
        margin-bottom: 1px;
        object-fit: cover;
      }
    }
    .no-user{
      height: 33px;
      line-height: 33px;
      margin-left: 20px;
      color: #999;
    }
  }
  ::v-deep .el-tabs__item{
    margin: 0 20px;
    padding: 0;
    &:nth-child(2){
      margin-left: 0;
    }
    &:last-child{
      margin-right: 0;
    }
    &.is-active{
      border-bottom: 2px solid $color-primary-light-6;
    }
  }
  .add-users-btn {
    height: 28px;
    border-radius: 4px;
    margin-bottom: 12px;
    margin-left: 12px;
    padding: 0 15px;
  }
}


::v-deep .el-tabs{
  margin-bottom: 10px;
  .el-tabs__active-bar{
    height: 0;
  }
  .el-tabs__nav-wrap {
    // background: #f5f5f5;
    padding-left: 20px;
    border-bottom: 1px solid #e8e8e8;
  }
  .el-tabs__nav-wrap::after{
    height: 0!important;
  }
}

.el-tag {
  margin-left: 12px;
}

.base-timeline{
  margin-bottom: 20px;
}

.btn-group{
  position: absolute;
  bottom: 0;
  right: 0;
  width: 100%;
  padding: 10px;
  background: #f5f5f5;
  text-align: right;
  .el-button--danger{
    &:hover, &:active {
      background: #f56c6c;
      border-color: #f56c6c;
      opacity: 0.8;
      color: #fff;
    }
  }
}
</style>

<style lang="scss" scoped>
  .dialog-title {
    display: flex;
    align-items: center;
    padding: 0;
    i {
      color: $color-danger;
      font-weight: 700;
    }
  }
  .dialog-content {
    display: flex;
    flex-direction: column;
    .el-radio:nth-child(1) {
      margin-bottom: 7px;
    }
  }

  ::v-deep .el-dialog .el-dialog__header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #fff;
    padding: 8px 20px;
  }
  ::v-deep .el-dialog__headerbtn {
    position: initial;
  }
  ::v-deep .el-dialog__body {
    padding: 15px 20px;
  }
  ::v-deep .el-dialog .el-dialog__footer {
    border-top: none;
  }
  .agendainfo-desc {
    .descr-content {
      overflow: hidden;
      font-size: 14px;
      font-weight: 400;
      color: #595959;
      line-height: 22px;
      word-break: break-word;
    }
    .more-desc {
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      line-clamp: 2;
      -webkit-box-orient: vertical;
    }
  }
  .descr-more {
    width: 80px;
    font-size: 14px;
    font-weight: 400;
    color: $color-primary-light-6;
    line-height: 22px;
    cursor: pointer;
    margin-left: 24px;
  }
</style>